//
//  JWLeftTabBar.m
//  JWCustomLeftTabBar
//
//  Created by sunjiawei on 2022/12/26.
//

#import "JWLeftTabBar.h"

@implementation JWLabel

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    UIEdgeInsets insets = self.edgeInsets;
    CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets) limitedToNumberOfLines:numberOfLines];
    rect.origin.x -= insets.left;
    rect.origin.y -= insets.top;
    rect.size.width += (insets.left + insets.right);
    rect.size.height += (insets.top + insets.bottom);
    return rect;
}

- (void)drawTextInRect:(CGRect)rect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}

@end

@implementation JWLeftTabBarItem

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    return CGRectMake((self.bounds.size.width-24)/2, 3, 24, 24);
}
/// title的位置
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    return CGRectMake(0, 29, self.bounds.size.width, 14);
}

#pragma mark - get
- (JWLabel *)numLa {
    if (!_numLa) {
        _numLa = [JWLabel new];
        _numLa.textColor = UIColor.whiteColor;
        _numLa.font = [UIFont systemFontOfSize:9.0];
        _numLa.backgroundColor = HexRGB(0xFB602C);
        _numLa.textAlignment = NSTextAlignmentCenter;
        _numLa.layer.borderColor = UIColor.whiteColor.CGColor;
        _numLa.layer.borderWidth = 1;
        _numLa.layer.masksToBounds = YES;
        _numLa.layer.cornerRadius = 13/2.0;
        _numLa.edgeInsets = UIEdgeInsetsMake(0, 4, 0, 4);
        [self addSubview:_numLa];
        [_numLa mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(13);
            make.width.mas_greaterThanOrEqualTo(13);
            make.centerX.equalTo(self.imageView.mas_right);
            make.centerY.equalTo(self.imageView.mas_top);
        }];
    }
    return _numLa;
}

@end

@interface JWLeftTabBar ()
/// 头像
@property (nonatomic, strong) UIImageView *avatarImageView;
/// item数组
@property (nonatomic, strong) NSMutableArray <JWLeftTabBarItem *> *itemArr;
/// item动图数组
@property (nonatomic, strong) NSMutableArray *itemGifImageArr;
/// 当前选中
@property (nonatomic, assign) NSUInteger curSelectIndex;
@end

@implementation JWLeftTabBar

- (instancetype)init {
    if (self = [super init]) {
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    
    self.backgroundColor = HexRGB(0xFFFFFF);
    
    [self addSubview:self.avatarImageView];
    
}

/// 加载item
- (void)loadAllItems {
    
    for (JWLeftTabBarItem *item in self.itemArr) {
        
        [self addSubview:item];
        
        if ([self.itemArr indexOfObject:item] == 0) {
            // 第一个
            [item mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.height.mas_equalTo(46);
            }];
        } else {
            JWLeftTabBarItem *lastitem = [self.itemArr objectAtIndex:[self.itemArr indexOfObject:item]-1];
            
            [item mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.height.mas_equalTo(46);
                make.top.equalTo(lastitem.mas_bottom).offset(30);
            }];
        }
    }
    
    if (self.itemArr.count%2 == 0) {
        // 双数 取中位数 上一个
        NSInteger index = self.itemArr.count/2 - 1;
        // 对应item
        JWLeftTabBarItem *item = self.itemArr[index];
        
        [item mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(-(38+46));
        }];
    } else {
        // 单数 取中位数
        NSInteger index = self.itemArr.count/2;
        // 对应item
        JWLeftTabBarItem *item = self.itemArr[index];
        
        [item mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(-46);
        }];
    }
    
}

/// 移除所有item
- (void)removeAllItems {
    self.curSelectIndex = 0;
    if (self.itemArr.count == 0) {
        return;
    }
    for (JWLeftTabBarItem *item in self.itemArr) {
        [item removeFromSuperview];
    }
    [self.itemArr removeAllObjects];
    [self.itemGifImageArr removeAllObjects];
}

/// 添加item
/// @param title 标题
/// @param image 未选中图片
/// @param selectedImage 选中图片
/// @param gif 动图
- (void)addItemWithTitle:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage gif:(NSString *)gif {
    // 为空校验
    if (![title isNotBlank] || ![image isNotBlank] || ![selectedImage isNotBlank]) {
        return;
    }
    
    JWLeftTabBarItem *item = [JWLeftTabBarItem buttonWithType:UIButtonTypeCustom];
    item.titleLabel.font = [UIFont systemFontOfSize:10.0];
    item.titleLabel.textAlignment = NSTextAlignmentCenter;
    item.adjustsImageWhenHighlighted = NO;
    [item setTitle:title forState:UIControlStateNormal];
    [item setTitleColor:HexRGB(0x333333) forState:UIControlStateNormal];
    [item setTitleColor:HexRGB(0xAF5DFF) forState:UIControlStateSelected];
    [item setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [item setImage:[UIImage imageNamed:selectedImage] forState:UIControlStateSelected];
    [item setTitleColor:HexRGB(0x333333) forState:UIControlStateNormal | UIControlStateHighlighted];
    [item setTitleColor:HexRGB(0xAF5DFF) forState:UIControlStateSelected | UIControlStateHighlighted];
    [item setImage:[UIImage imageNamed:image] forState:UIControlStateNormal | UIControlStateHighlighted];
    [item setImage:[UIImage imageNamed:selectedImage] forState:UIControlStateSelected | UIControlStateHighlighted];
    [item addTarget:self action:@selector(handleItemClickEvent:) forControlEvents:UIControlEventTouchUpInside];

    [self.itemArr addObject:item];
    // gif图片数组存起来
    if ([gif isNotBlank]) {
        [self.itemGifImageArr addObject:[self getImageFromGifResource:gif]];
    } else {
        [self.itemGifImageArr addObject:@[]];
    }
}

/// 设置item选中
/// @param index 位置
- (void)setSelectItemWithIndex:(NSInteger)index {
    if (index >= self.itemArr.count) {
        return;
    }
    // 移除上一次的选中
    if (self.curSelectIndex < self.itemArr.count) {
        JWLeftTabBarItem *lastItem = self.itemArr[self.curSelectIndex];
        lastItem.selected = NO;
    }
    // 设置选中
    self.curSelectIndex = index;
    JWLeftTabBarItem *curItem = self.itemArr[self.curSelectIndex];
    curItem.selected = YES;
    
    // 加载动画
    if ([self.itemGifImageArr[index] count]) {
        curItem.imageView.animationImages = self.itemGifImageArr[index];
        curItem.imageView.animationDuration = 0.5;
        curItem.imageView.animationRepeatCount = 1;
        [curItem.imageView startAnimating];
    }
}

/// 设置数字角标
/// @param index 位置
/// @param num 数字
- (void)setItemBadgeWithIndex:(NSInteger)index num:(NSInteger)num {
    
    if (index >= self.itemArr.count) {
        return;
    }
    
    JWLeftTabBarItem *item = self.itemArr[index];

    if (num == 0) {
        item.numLa.hidden = YES;
        return;
    }
    NSString *numStr;
    if (num > 99) {
        numStr = @"99+";
    } else {
        numStr = [NSString stringWithFormat:@"%ld",num];
    }
    item.numLa.text = numStr;
    item.numLa.hidden = NO;

}

/// item点击事件处理
/// @param sender item
- (void)handleItemClickEvent:(JWLeftTabBarItem *)sender {
    
    BOOL isShouldSelect = YES;
    if ([self.delegate respondsToSelector:@selector(leftTabbar:shouldSelectWithIndex:)]) {
        isShouldSelect = [self.delegate leftTabbar:self shouldSelectWithIndex:[self.itemArr indexOfObject:sender]];
    }
    
    if (isShouldSelect) {
        // 可以点击
        [self setSelectItemWithIndex:[self.itemArr indexOfObject:sender]];
        if ([self.delegate respondsToSelector:@selector(leftTabbar:didSelectWithIndex:)]) {
            [self.delegate leftTabbar:self didSelectWithIndex:[self.itemArr indexOfObject:sender]];
        }
    }
}

/// 获取git图片数组
/// @param resource 资源
- (NSArray *)getImageFromGifResource:(NSString *)resource {
    NSMutableArray *imageArray = [NSMutableArray array];
    
    // 获取gif url
    NSURL *url = [[NSBundle mainBundle] URLForResource:resource withExtension:@"gif"];
    // 转换为图片源
    CGImageSourceRef gifImageSourceRef = CGImageSourceCreateWithURL((CFURLRef)url, nil);
    // 获取图片个数
    size_t framesCount = CGImageSourceGetCount(gifImageSourceRef);
    for (size_t i=0; i<framesCount; i++) {
        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifImageSourceRef, i, nil);
        UIImage *image = [UIImage imageWithCGImage:imageRef];
        
        [imageArray addObject:image];
        
        CFRelease(imageRef);
    }
    
    return imageArray;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

#pragma mark - get
- (UIImageView *)avatarImageView {
    if (!_avatarImageView) {
        _avatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(12, kStatusBarHeight+21, 46, 46)];
        _avatarImageView.userInteractionEnabled = YES;
        _avatarImageView.backgroundColor = UIColor.redColor;
    }
    return _avatarImageView;
}
- (NSMutableArray *)itemArr {
    if (!_itemArr) {
        _itemArr = [NSMutableArray array];
    }
    return _itemArr;
}
- (NSMutableArray *)itemGifImageArr {
    if (!_itemGifImageArr) {
        _itemGifImageArr = [NSMutableArray array];
    }
    return _itemGifImageArr;
}

@end
